//go:generate goversioninfo -icon=resource/icon.ico -manifest=resource/goversioninfo.exe.manifest
package main

import (
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	jrpc "intranetWs/ion-sfu/cmd/signal/json-rpc"
	"intranetWs/router"
	"intranetWs/ws"
	"log"
	"net"
	"os"
	"time"
)

var (
	RunMode string
	localIP net.IP
	tcpPort int
	udpPort int
	jPort   string
	JConfig string
)

func parse() bool {
	flag.StringVar(&RunMode, "m", "debug", "tpc port")
	flag.IntVar(&tcpPort, "t", 9244, "tpc port")
	flag.IntVar(&udpPort, "u", 9244, "udp port")
	flag.StringVar(&jPort, "j", "9245", "jsonrpc port")
	flag.StringVar(&JConfig, "c", "./conf/config.toml", "json-rpc config")
	help := flag.Bool("h", false, "help info")
	flag.Parse()
	if *help {
		return false
	}
	return true
}

// 入口程序
// go generate
// go build -o JcrdLocalServer.exe -ldflags="-linkmode internal"
func main() {
	if !parse() {
		showHelp()
		os.Exit(-1)
	}
	// fmt.Println("JConfig```", JConfig)
	// websocket service
	go ws.WebsocketManager.Start()
	go ws.WebsocketManager.SendService()
	go ws.WebsocketManager.SendGroupService()
	go ws.WebsocketManager.SendAllService()

	lp, err := externalIP()
	// 没找到本机IP
	if err != nil {
		fmt.Println("err:", err.Error())
		return
	}
	localIP = lp
	// udp service

	go udpPackage()
	// json-rpc service
	go jrpc.Run(JConfig, ":"+jPort)
	r := router.SetupRouter(RunMode)
	r.Run(":" + fmt.Sprintf("%d", tcpPort))

	log.Println("end...")
	// TestStream()

}

func showHelp() {
	//fmt.Printf("Usage:%s {params}\n", os.Args[0])
	fmt.Println("      -m {SetMode sets gin mode according to input string:debug|release|test}")
	fmt.Println("      -t {tpc port}")
	fmt.Println("      -u {udp port}")
	fmt.Println("      -h (show help info)")
}

func externalIP() (net.IP, error) {
	ifaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}
	for _, iface := range ifaces {
		if iface.Flags&net.FlagUp == 0 {
			continue // interface down
		}
		if iface.Flags&net.FlagLoopback != 0 {
			continue // loopback interface
		}
		addrs, err := iface.Addrs()
		if err != nil {
			return nil, err
		}
		for _, addr := range addrs {
			ip := getIpFromAddr(addr)
			if ip == nil {
				continue
			}
			return ip, nil
		}
	}
	return nil, errors.New("not connected to the network")
}

func getIpFromAddr(addr net.Addr) net.IP {
	var ip net.IP
	switch v := addr.(type) {
	case *net.IPNet:
		ip = v.IP
	case *net.IPAddr:
		ip = v.IP
	}
	if ip == nil || ip.IsLoopback() {
		return nil
	}
	ip = ip.To4()
	if ip == nil {
		return nil // not an ipv4 address
	}

	return ip
}

type packageInfo struct {
	Id     int    `json:"id"`
	Type   string `json:"type"`
	Name   string `json:"name"`
	WsHost string `json:"ws"`
	Port   int    `json:"port"`
	//Route  string `json:"route"`
}

func udpPackage() {

	ip_ := localIP.To4()
	fmt.Println("localIp", localIP)
	// 这里设置发送者的IP地址，自己查看一下自己的IP自行设定
	/*laddr := net.UDPAddr{
		IP:   net.IPv4(ip_[0], ip_[1], ip_[2], ip_[3]),
		Port: udpPort + 1,
	}*/

	// 这里设置接收者的IP地址为广播地址
	raddr := net.UDPAddr{
		IP:   net.IPv4(255, 255, 255, 255),
		Port: udpPort,
	}
	conn, err := net.DialUDP("udp", nil, &raddr)
	if err != nil {
		println(err.Error())
		return
	}
	//mem.SwapMemory()
	n, _ := os.Hostname()
	var info packageInfo
	info.Name = n
	info.WsHost = ip_.String()
	info.Type = "ws-service"
	info.Port = tcpPort
	//info.Route = "test"
	i := 0
	for {
		i++
		info.Id = i
		jsonInfo, _ := json.Marshal(info)
		time.Sleep(time.Duration(3) * time.Second)
		mess := fmt.Sprintf("广播消息-%d-%s", i, ip_)
		fmt.Println(mess)
		_, err := conn.Write(jsonInfo)
		if err != nil {
			fmt.Println(err)
		}
	}
}
